package com.czr.service.collect;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czr.entity.Collect;
import com.czr.entity.CollectCategory;
import com.czr.mapper.CollectMapper;
import com.czr.service.collectcategory.CollectCategoryService;
import com.czr.vo.CollectVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: czr
 * Version: 1.0
 * Create Date Time: 2021/12/22 17:11.
 */
@Service
@Slf4j
public class CollectSqlAllServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    @Autowired
    private CollectCategoryService collectCategoryService;

    /**
     * 会查询大量的SQL，但是这种方式可以分页
     * @return
     */
    @Override
    public List<CollectVo> findList() {
        // 查询分类数据
        List<CollectCategory> collectCategorylist = collectCategoryService.list();

        // 1：查询表中所有的收藏夹数据
        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Collect::getStatus, 1);
        List<Collect> collects = this.list(queryWrapper);
        // 2：根据分类id进行排序
        Map<Integer, List<Collect>> collectMap = collects.stream().collect(Collectors.groupingBy(Collect::getCategoryId));

        List<CollectVo> collectVoList = new ArrayList<>();
        // 3：根据分类id进行收藏夹查询
        collectMap.entrySet().forEach(entry -> {
            log.info("kety："+ entry.getKey()+"  value："+entry.getValue());
            CollectVo collectVo = new CollectVo();
            collectVo.setCategoryId(entry.getKey());

            //  查询分类表id匹配collect表分类id选取title
            Optional<CollectCategory> first = collectCategorylist.stream().filter(collectCategory ->
                    collectCategory.getId().equals(entry.getKey())).findFirst();
            // 避免No value present
            if (first.isPresent()) {
                collectVo.setCategoryTitle(first.get().getCategoryTitle());
            }

            collectVo.setCollectList(entry.getValue());

            collectVoList.add(collectVo);

        });
        // 4：返回即可

        return collectVoList;
    }

}
